package cn.codelab.gatewaydemo.routepredicate;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

/**
 * @author Seven
 * @description
 * @博客：https://codelab7.cn
 * @Gitee https://gitee.com/it-codelab
 * @Copyright 公众号：Seven的代码实验室
 */
@Component
@Slf4j
public class TestDemoRoutePredicateFactory extends AbstractRoutePredicateFactory<TestDemoRoutePredicateFactory.Config> {

    public TestDemoRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("name");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                log.info("调用了TestDemoRoutePredicateFactory" + config.getName());
                if (Objects.equals("seven", config.getName())) {
                    return true;
                }
                return false;
            }
        };
    }

    // 用于接收配置文件中断言信息
    @Validated
    public static class Config{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
